#include <stdio.h>
#include <stdlib.h>

#define searchStr0 "git clone git@codeup.aliyun.com:60d476b0a3a2bac55d3123c6/tssl/privacy_computation"
//#define searchStr1 "base64.b64encode("

int foundCount = 0;
void printNear(char* buff, int bufSize, char* p) {
	char filePath[64];
	char* start;
	char* end;
	char* buffEnd;
	FILE* fp;
	
	printf("found %d !!!! \n", foundCount);
	
	sprintf(filePath, "/data/found%d", foundCount);
	
	start = p-4096;
	if (start < buff) {
		start = buff;
	}
	end = p+4096;
	buffEnd = buff + bufSize;
	if (end > buffEnd) {
		end = buffEnd;
	}
	
	fp = fopen(filePath, "wb");
	fwrite(start, 1, end-start, fp);
	fclose(fp);

	++foundCount;
}

void search(char* buff, int bufSize) {
	int sizeArray[] = {sizeof(searchStr0)-1/*, sizeof(searchStr1)-1*/};
	int i;
	int maxSize = 0;
	char* lastP;
	char* p;
	
	for (i=0; i<sizeof(sizeArray)/sizeof(int); ++i) {
		if (maxSize < sizeof(sizeArray[i])) {
			maxSize = sizeof(sizeArray[i]);
		}
	}

	lastP = buff + (bufSize-maxSize);
	p = buff;
	while (p <= lastP) {
		if (0 == memcmp(p, searchStr0, sizeof(searchStr0)-1)) {
			printNear(buff, bufSize, p);
			if (foundCount > 20) break;
			p += sizeof(searchStr0)-1;
			continue;
		}
		/*if (0 == memcmp(p, searchStr1, sizeof(searchStr1)-1)) {
			printNear(buff, bufSize, p);
			if (foundCount > 20) break;
			p += sizeof(searchStr1)-1;
			continue;
		}*/
		/*if (0 == memcmp(p, searchStr2, sizeof(searchStr2)-1)) {
			printNear(buff, bufSize, p);
			if (foundCount > 20) break;
			p += sizeof(searchStr2)-1;
			continue;
		}*/
		
		++p;
	}
}

int main() {
    FILE* fp = fopen("/data/rootAllFiles", "rb");

	int bufSize = 100<<20;
	char* buff = malloc(bufSize);
	long blockIdx = 400;

	printf("start\n");

	if (blockIdx > 0) {
		fseek(fp, bufSize*blockIdx, SEEK_SET);
	}
	
	while (1) {
		int readSize = fread(buff, 1, bufSize, fp);
		
		search(buff, bufSize);
		printf("%d search block end .\n", (int)blockIdx);
		
		if (foundCount > 20) break;
		
		if (readSize < bufSize) {
			break;
		}
		
		++blockIdx;
	}

    fclose(fp);
	free(buff);

    printf("end\n");
    return 0;
}